import {GameEngine} from "./gameEngine";
import { myPlane } from "./myPlane";


export class Bullets {
  public el: HTMLDivElement;
  private timer: any;
  private dieTimer: any;
  private id: number;
  constructor() {
    this.timer = 0;
    this.id = parseInt((Math.random() * 10000) + "")
    this.el = document.createElement("div");
    //把子弹添加到游戏引擎的界面
    GameEngine.el.appendChild(this.el);
    this.el.className = "bullet";
    let left = myPlane.el.offsetLeft + myPlane.el.offsetWidth / 2 - this.el.offsetWidth / 2 + "px"
    this.el.style.left = left;
    this.el.style.top = myPlane.el.offsetTop - 10 + "px";

    GameEngine.bullets[Number(this.id)] = this //this是实例对象

  }
  move() {
    this.timer = setInterval(() => {
      this.el.style.top = this.el.offsetTop - 10 + "px";
      if (this.el.offsetTop <= 0) {
        this.boom();
        clearInterval(this.timer);
      }
    }, 30)
  }

  boom() {
    this.el.className = "bullet-die";
    let imgIndex = 0;
    this.dieTimer = setInterval(() => {
      imgIndex++;
      this.el.style.backgroundImage = `url(./images/die${imgIndex}.png)`;
      if (imgIndex >= 2) {
        clearInterval(this.dieTimer);
        this.el.remove();
        GameEngine.bullets.splice(this.id, 1);
      }
    }, 30)
  }
  hide() {
    this.el.remove();
    GameEngine.bullets.splice(this.id, 1);
  }
}
